//
//  DateTimeSelectView.m
//  MClient
//
//  Created by  史正烨 on 10-9-7.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "DateTimeSelectView.h"
#import "MCFunction.h"
#import "MCControl.h"

@interface DateTimeSelectView(Private)
- (id)initWithView:(MCControl*)view withMode:(UIDatePickerMode)mode;
- (void)layoutFrame:(CGRect)frame;
@end

@implementation DateTimeSelectView
@synthesize textFieldView;
@synthesize fieldData;
@synthesize isShown;

static DateTimeSelectView *dateTimeSelectInstance = nil;
#define nDateTimeToolBarHeight    28
#define nDateTimePickerHeight     nPickerHeight

+ (DateTimeSelectView *)instance {
	@synchronized(self) {
		if (dateTimeSelectInstance == nil) {
			dateTimeSelectInstance = [[self alloc] initWithView:nil withMode:UIDatePickerModeDateAndTime]; // assignment not done here
		}
	}
	return dateTimeSelectInstance;
}

- (id)initWithView:(MCControl*)view withMode:(UIDatePickerMode)mode {
    if (self = [super initWithFrame:CGRectZero]) {
        // Initialization code
		textFieldView = view;
		isShown = NO;
		
		datePicker = [[MCDatePicker alloc] initWithFrame:CGRectZero];
		[self addSubview:datePicker];
		
		toolBar = [[UIToolbar alloc] initWithFrame:CGRectZero];
		[self addSubview:toolBar];
		toolBar.barStyle = UIBarStyleDefault;
		[toolBar sizeToFit];
		MCUserDefaults *defaults = [MCUserDefaults instance];
		toolBar.tintColor = defaults.skin_navigationBarColor;
		
		NSString *title;
		if (mode == UIDatePickerModeDateAndTime) {
			//datePicker.datePickerMode = UIDatePickerModeDateAndTime;
			datePicker.mode = MCDatePickerModeDateTime;
			title = @"设置日期和时间";
		} else {
			//datePicker.datePickerMode = UIDatePickerModeDate;
			datePicker.mode = MCDatePickerModeDate;
			title = @"设置日期";
		}
		UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleBordered target:self action:@selector(selectCancelAction)];	
		UIBarButtonItem *flexItem1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
		titleBtn = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStylePlain target:nil action:nil];
		UIBarButtonItem *flexItem2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
		UIBarButtonItem *confirmBtn = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStyleBordered target:self action:@selector(selectAction)];
		
		[toolBar setItems:[NSArray arrayWithObjects:cancelBtn, flexItem1, titleBtn, flexItem2, confirmBtn, nil] animated:NO];
		[cancelBtn release];
		[flexItem1 release];
		[flexItem2 release];
		[confirmBtn release];
		
		
    }
    return self;
}

- (void)layoutFrame:(CGRect)frame
{
	self.frame = CGRectMake(0, CGRectGetMaxY(frame), CGRectGetMaxX(frame), nDateTimePickerHeight+nDateTimeToolBarHeight);
	self.autoresizingMask = nMCViewAutoresizingMask|UIViewAutoresizingFlexibleHeight;
	datePicker.frame = CGRectMake(0, nDateTimeToolBarHeight, CGRectGetMaxX(frame), nDateTimePickerHeight);
	datePicker.autoresizingMask = nMCViewAutoresizingMask|UIViewAutoresizingFlexibleHeight;
	toolBar.frame = CGRectMake(0, 0, CGRectGetMaxX(frame), nDateTimeToolBarHeight);
	toolBar.autoresizingMask = nMCViewAutoresizingMask|UIViewAutoresizingFlexibleHeight;
}

- (void)dealloc {
	[titleBtn release];
	[datePicker release];
	[toolBar release];
    [super dealloc];
}

- (void)return2Parent
{
	parentViewController.navigationController.navigationBar.userInteractionEnabled = YES;
	[self removeFromSuperview];
	isShown = !isShown;
}

- (void)selectCancelAction
{
	CGRect originFrame = self.frame;
	CGRect finalFrame = CGRectMake(originFrame.origin.x, 
								   CGRectGetMinY(originFrame)+originFrame.size.height, 
								   originFrame.size.width, 
								   originFrame.size.height);
	
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.3];
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDidStopSelector:@selector(return2Parent)];
	self.frame = finalFrame;
	[UIView commitAnimations];  
}

- (void)selectAction
{
	[self selectCancelAction];
	
	if (textFieldView) {
		NSCalendar* calendar = [NSCalendar currentCalendar];
		NSUInteger unFlag = NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit |
		NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit |
		NSSecondCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit;
		NSDateComponents *comps = [calendar components:unFlag fromDate:datePicker.date];
		
		if (datePicker.mode == MCDatePickerModeDateTime) {
			textFieldView.text = [NSString stringWithFormat:@"%04d-%02d-%02d %d:%02d:%02d", 
								  comps.year, comps.month, comps.day, comps.hour, comps.minute, comps.second];
		} else {
			textFieldView.text = [NSString stringWithFormat:@"%04d-%02d-%02d", 
								  comps.year, comps.month, comps.day];
		}
		[fieldData setObject:textFieldView.text forKey:@"value"];
		textFieldView = nil;
	}
}

- (void)show:(MCViewController*)parentController withMode:(UIDatePickerMode)mode
{
	//datePicker.datePickerMode = mode;
	NSString *title;
	if (mode == UIDatePickerModeDateAndTime) {
		datePicker.mode = MCDatePickerModeDateTime;
		//datePicker.datePickerMode = UIDatePickerModeDateAndTime;
		if (nil != [fieldData objectForKey:@"value"] && ![@"" isEqualToString:[fieldData objectForKey:@"value"]]) {
			datePicker.date = [MCFunction DateFromString:[fieldData objectForKey:@"value"] format:@"yyyy-MM-dd HH:mm:ss"];
		}else {
			datePicker.date = [NSDate date];
		}

		title = @"设置日期和时间";
	} else {
		//datePicker.datePickerMode = UIDatePickerModeDate;
		datePicker.mode = MCDatePickerModeDate;
		if (nil != [fieldData objectForKey:@"value"] && ![@"" isEqualToString:[fieldData objectForKey:@"value"]]) {
			datePicker.date = [MCFunction DateFromString:[fieldData objectForKey:@"value"] format:@"yyyy-MM-dd"];
		}else {
			datePicker.date = [NSDate date];
		}

		title = @"设置日期";
	}
		
	titleBtn.title = title;
	
	if (!isShown) {
		[self layoutFrame:parentController.clientView.bounds];
		parentViewController = parentController;
		[parentViewController.clientView addSubview:self];
		parentViewController.navigationController.navigationBar.userInteractionEnabled = NO;
		
		CGRect originFrame = self.frame;
		CGRect finalFrame = CGRectMake(originFrame.origin.x, 
									   CGRectGetMinY(originFrame)-originFrame.size.height, 
									   originFrame.size.width, 
									   originFrame.size.height);
		
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.3];
		self.frame = finalFrame;
		[UIView commitAnimations];
		isShown = !isShown;
	}
}
@end

@implementation MCDatePicker

- (id)initWithFrame:(CGRect)frame
{
	if (self = [super initWithFrame:frame]) {
		_date = [[NSDate date] retain];
		_picker = [[UIPickerView alloc] initWithFrame:self.bounds];
		NSCalendar* calendar = [NSCalendar currentCalendar];
		NSUInteger unFlag = NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit |
		NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit |
		NSSecondCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit;
		NSDateComponents *comps = [calendar components:unFlag fromDate:[NSDate date]];
		_curMonth = comps.month;
		_localYear = comps.year-50;
		[self addSubview:_picker];
		_picker.delegate = self;
		_picker.dataSource = self;
		_picker.showsSelectionIndicator = YES;
	}
	
	return self;
}

- (void)dealloc
{
	[_picker release];
	[_date release];
	[super dealloc];
}

- (NSDate*)date
{
	if (_mode == MCDatePickerModeDate) {
		int nYear = [_picker selectedRowInComponent:0]+_localYear;
		int nMonth = [_picker selectedRowInComponent:1]+1;
		int nDay = [_picker selectedRowInComponent:2]+1;
		return [MCFunction DateFromString:[NSString stringWithFormat:@"%04d-%02d-%02d",nYear,nMonth,nDay] format:@"yyyy-MM-dd"];
	}
	if (_mode == MCDatePickerModeDateTime) {
		int nYear = [_picker selectedRowInComponent:0]+_localYear;
		int nMonth = [_picker selectedRowInComponent:1]+1;
		int nDay = [_picker selectedRowInComponent:2]+1;
		int nHour = [_picker selectedRowInComponent:3];
		int nMinute = [_picker selectedRowInComponent:4];
		return [MCFunction DateFromString:[NSString stringWithFormat:@"%04d-%02d-%02d %02d:%02d",nYear,nMonth,nDay, nHour,nMinute] 
								   format:@"yyyy-MM-dd hh:mm"];
	}
	
	return nil;
}

- (void)setDate:(NSDate *)dt
{
	NSCalendar* calendar = [NSCalendar currentCalendar];
	NSUInteger unFlag = NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit |
	NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit |
	NSSecondCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit;
	NSDateComponents *comps = [calendar components:unFlag fromDate:dt];
	
	_curMonth = comps.month;
	_date = dt;
	if (_mode == MCDatePickerModeDate) {
		[_picker selectRow:comps.year-_localYear inComponent:0 animated:NO];
		[_picker selectRow:_curMonth-1 inComponent:1 animated:NO];
		[_picker selectRow:comps.day-1 inComponent:2 animated:NO];
	}
	if (_mode == MCDatePickerModeDateTime) {
		[_picker selectRow:comps.year-_localYear inComponent:0 animated:NO];
		[_picker selectRow:_curMonth-1 inComponent:1 animated:NO];
		[_picker selectRow:comps.day-1 inComponent:2 animated:NO];
		[_picker selectRow:comps.hour inComponent:3 animated:NO];
		[_picker selectRow:comps.minute inComponent:4 animated:NO];
	}
}

- (MCDatePickerMode)mode
{
	return _mode;
}
- (void)setMode:(MCDatePickerMode)md
{
	_mode = md;
	[_picker reloadAllComponents];
}

- (void)layoutSubviews
{
	_picker.frame = self.bounds;
}

// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	if (_mode == MCDatePickerModeDate) {
		return 3;
	}
	if (_mode == MCDatePickerModeDateTime) {
		return 5;
	}
	
	return 0;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	switch (component) {
		case 0:// 年
			return 100;//100年供选择
		case 1:// 月
			return 12;
		case 2:// 日
			return (_curMonth==2)?28:(_curMonth==4||_curMonth==6||_curMonth==9||_curMonth==11)?30:31;
		case 3:// 时
			return 24;
		case 4:// 分
			return 60;
		default:
			return 0;
	}
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
	switch (component) {
		case 0:// 年*
			if (_mode == MCDatePickerModeDateTime) {
				return [NSString stringWithFormat:@"%d", _localYear+row];
			} else {
				return [NSString stringWithFormat:@"%d年", _localYear+row];
			}
		case 1:// 月
			return [NSString stringWithFormat:@"%d月", row+1];
		case 2:// 日
			return [NSString stringWithFormat:@"%d日", row+1];
		case 3:// 时
			return [NSString stringWithFormat:@"%d时", row];
		case 4:// 分
			return [NSString stringWithFormat:@"%d分", row];
		default:
			return nil;
	}
	
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
	if (_mode == MCDatePickerModeDate) {
		return 98;
	}
	if (_mode == MCDatePickerModeDateTime) {
		if (component == 0) {
			return 66;
		}
		return 58;
	}
	
	return 0;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	if (component == 1) {
		int nCurDaySelect = [pickerView selectedRowInComponent:2];
		_curMonth = row + 1;
		int nCurMonthDays = (_curMonth==2)?27:(_curMonth==4||_curMonth==6||_curMonth==9||_curMonth==11)?29:30;
		nCurDaySelect = nCurDaySelect > nCurMonthDays ? nCurMonthDays : nCurDaySelect;
		[pickerView selectRow:nCurDaySelect inComponent:2 animated:NO];
		[pickerView reloadComponent:2]; 
	}
}

@end

